package com.tanxiuxin.YiWaiMai.controller;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanxiuxin.YiWaiMai.common.Result;
import com.tanxiuxin.YiWaiMai.pojo.Category;
import com.tanxiuxin.YiWaiMai.service.CateGoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *     分类管理
 */
@RestController
@RequestMapping("/category")
public class CateGoryController {

    @Autowired
    private CateGoryService cateGoryService;


    /**
     *     新增分类
     * @param category
     * @return
     */
    @PostMapping
    @CacheEvict(value = "CateGoryCache" , allEntries = true) // 表示删除 CateGoryCache 下所有缓存数据
    public Result<String> save(@RequestBody Category category){
        cateGoryService.save(category);
        return Result.success("新增分类成功");
    }

    /**
     *    分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page , int pageSize){
        // 构造分页构造器
        Page<Category> pageInfo = new Page<>(page , pageSize);
        // 构造条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        // 添加排序条件,根据 数据库字段 sort 进行排序
        queryWrapper.orderByAsc(Category::getSort);

        // 进行分页查询
        cateGoryService.page(pageInfo , queryWrapper);
        return Result.success(pageInfo);
    }

    /**
     *        根据 id 删除分类
     * @param id
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "CateGoryCache" , allEntries = true) // 表示删除 CateGoryCache 下所有缓存数据
    public Result<String> delete(Long id){

        cateGoryService.remove(id);

        return Result.success("分类删除成功");
    }

    /**
     *        根据 id 修改分类信息
     * @param category
     * @return
     */
    @PutMapping
    @CacheEvict(value = "CateGoryCache" , allEntries = true) // 表示删除 CateGoryCache 下所有缓存数据
    public Result<String> update(@RequestBody Category category){
        cateGoryService.updateById(category);
        return Result.success("修改分类信息成功");
    }

    /**
     *      根据条件查询分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "CateGoryCache" , key = "#category.type + '_' + #category.sort")
    public Result<List<Category>> list(Category category){
        // 条件构造器
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 添加条件
        lambdaQueryWrapper.eq(category.getType() != null , Category::getType , category.getType());
        // 添加排序条件
        lambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = cateGoryService.list(lambdaQueryWrapper);
        return Result.success(list);
    }
}
